<template>
  <div class="app-container">
    <!-- <el-row :gutter="20"> -->
    <el-col :span="4" :xs="24">
      <div class="head-container" v-if="false">
        <el-input
          v-model="name"
          placeholder="请输入分组名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />
      </div>
      <div class="head-container" v-if="false">
        <el-tree
          :data="deptOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
        />
      </div>
    </el-col>
    <!--用户数据-->
    <!-- <el-col :span="20" :xs="24"> -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="账号" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账号类型" prop="codeType">
        <el-select
          v-model="queryParams.codeType"
          placeholder="账号类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.chat_code_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属分组" prop="groupId">
        <el-select v-model="queryParams.groupId" placeholder="请选择所在分组">
          <el-option
            v-for="dict in groupList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="账号状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="账号状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.chat_code_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-female"
          size="mini"
          @click="handleLogin"
          >批量登录</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleUpdate(1)"
          >设置分组</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <!-- <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col> -->
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
         
          >删除</el-button
        >
         <!-- v-hasPermi="['system:user:remove']" -->
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      style="width: 100%"
      v-loading="loading"
      :data="chatUserList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="头像" align="center" prop="avatar">
        <template slot-scope="scope">
          <el-avatar :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="账号" align="center" prop="name" />
      <el-table-column label="所属分组" align="center" prop="groupName" />
      <el-table-column label="账号类型" align="center" prop="codeType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.chat_code_type"
            :value="scope.row.codeType"
          />
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.chat_user_type"
            :value="scope.row.type"
          />
        </template>
      </el-table-column>
      <el-table-column label="账号状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.chat_code_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createName" />
      <el-table-column label="导入时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(2, scope.row)"
            v-hasPermi="['system:user:edit']"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- </el-col>
    </el-row> -->

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="头像" prop="avatar" v-if="show">
          <div class="touxiang">
            <div class="pic">
              <img
                v-if="imageUrl"
                :src="imageUrl ? '' + imageUrl : '@/assets/avatar.gif'"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </div>
            <el-upload
              class="avatar-uploader"
              list-type="picture"
              ref="upload"
              accept=".jpg, .png"
              action=""
              :limit="1"
              :show-file-list="false"
              :file-list="fileList"
              :on-change="getFile"
              :before-upload="beforeUpload"
            >
              <el-button size="small" round>点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpeg格式的图片，且不超过2MB
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName" v-if="show">
          <el-input v-model="form.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="聊天账号" prop="name" v-if="show">
          <el-input v-model="form.name" disabled />
        </el-form-item>
        <el-form-item label="所属分组" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择所在分组">
            <el-option
              v-for="dict in groupList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      style="text-align: center"
      :title="upload.title"
      :visible.sync="upload.open"
      width="700px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="
          upload.url +
          '?updateSupport=' +
          upload.updateSupport +
          '&type=' +
          upload.type +
          '&typeCode=' +
          upload.typeCode +
          '&code=' +
          upload.code +
          '&mcc=' +
          upload.mcc +
          '&mnc=' +
          upload.mnc
        "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div style="margin-left: -10%">
            <label
              ><span style="margin-right: 5px; color: red">*</span
              >设备类型：</label
            >
            <el-select v-model="upload.type" placeholder="请选择设备类型">
              <el-option
                v-for="dict in dict.type.chat_user_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </div>
          <div style="margin-top: 10px; margin-left: -10%">
            <label
              ><span style="margin-right: 5px; color: red">*</span
              >账号类型：</label
            >
            <el-select v-model="upload.typeCode" placeholder="请选择账号类型">
              <el-option
                v-for="dict in dict.type.chat_code_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </div>
          <div style="margin-top: 10px; margin-left: -10%">
            <label
              ><span style="margin-right: 5px; color: red">*</span
              >IP国家：</label
            >
            <el-select
              v-model="upload.info1"
              placeholder="请选择国家"
              @change="getMcc"
              filterable
            >
              <el-option
                v-for="dict in countryList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
            <!-- <el-select
              style="width: 20%"
              v-model="upload.info2"
              placeholder="请选择运营商"
              @change="getMnc"
            >
              <el-option
                v-for="dict in mncList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select> -->
          </div>
          <div style="margin-top: 10px">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crypto from "crypto";
import {
  listChatUser,
  getChatUser,
  delChatUser,
  addChatUser,
  updateChatUser,
  batchLogin,
  groups,
} from "@/api/business/chatUser";
import { listCountryList } from "@/api/business/countryList";
import { listCountryCode } from "@/api/business/countryCode";

import {
  deptTreeSelect,
  listChatUserGroup,
} from "@/api/business/chatUserGroup";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: [
    "chat_user_type",
    "sys_user_sex",
    "chat_code_type",
    "chat_code_status",
  ],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 账号信息表格数据
      chatUserList: [],
      groupList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      name: undefined,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        type: "1",
        typeCode: "1",
        info1: undefined,
        info2: undefined,
        code: "",
        mcc: "",
        mnc: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/chatUser/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        nickName: undefined,
        status: undefined,
        codeType: undefined,
      },
      // 表单校验
      rules: {},
      show: true,
      // 上传头像地址
      imageUrl: "",
      //接收上传的文件
      fileList: [],
      imgStatus: true,
      countryList: [],
      mncList: [],
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getDeptTree();

    //获取分组列表
    listChatUserGroup({ showStatus: 1 }).then((response) => {
      var gruops = response.rows;
      var groupList = [];
      for (var i in gruops) {
        var info = {};
        info.value = gruops[i].id;
        info.label = gruops[i].name;
        groupList.push(info);
      }
      this.groupList = groupList;
    });

    //查询国家列表
    listCountryList({ type: "1" }).then((response) => {
      var gruops = response.rows;
      var list = [];
      for (var i in gruops) {
        var info = gruops[i];
        info.value = gruops[i].id;
        info.label = gruops[i].name;
        list.push(info);
      }
      this.countryList = list;
    });
  },
  methods: {
    encrypt(data, key) {
      const iv = "";
      const clearEncoding = "utf8";
      const cipherEncoding = "base64";
      const cipherChunks = [];
      const cipher = crypto.createCipheriv(
        "aes-128-ecb",
        Buffer.from(key, "base64"),
        iv
      );
      cipher.setAutoPadding(true);
      cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
      cipherChunks.push(cipher.final(cipherEncoding));
      return cipherChunks.join("");
    },
    getMcc(id) {
      for (var i in this.countryList) {
        var item = this.countryList[i];
        if (item.id == id) {
          this.upload.mcc = item.code;
        }
      }
    },
    getMnc(id) {
      for (var i in this.mncList) {
        var item = this.mncList[i];
        if (item.id == id) {
          this.upload.mnc = item.mnc;
        }
      }

      //查询运营商列表
      listCountryCode({ mainId: id }).then((response) => {
        var gruops = response.rows;
        var list = [];
        for (var i in gruops) {
          var info = gruops[i];
          info.value = gruops[i].id;
          info.label = gruops[i].name;
          list.push(info);
        }
        this.mccList = list;
      });
    },
    // 头像上传
    getFile(file, fileList) {
      if (this.imgStatus) {
        this.getBase64(file.raw).then((res) => {
          this.imageUrl = res;
          this.form.avatar = res;
        });
      }
    },
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传jpg类型的图片");
        return;
      }

      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const image = new Image();
        image.src = reader.result;
        image.onload = () => {
          this.imgWidth = image.width;
          this.imgHeight = image.height;
          if (image.width != 640 || image.height != 640) {
            this.$message.error("请上传像素为640*640的图片");
            return;
          }
        };
      };

      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return;
      }
      this.imgStatus = true;
    },
    //这里是文件转base64
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },

    /** 批量登录 */
    handleLogin() {
      const ids = this.ids;
      this.$modal
        .confirm("确认登录账号吗？")
        .then(() => {
          this.loading = true;
          batchLogin({ids:ids}).then((response) => {
          });
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "账号导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "business/chatUser/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listChatUser(this.queryParams).then((response) => {
        this.chatUserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.groupId = data.id;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        avatar: undefined,
        name: undefined,
        nickName: undefined,
        pwdKey: undefined,
        pwdSecret: undefined,
        groupId: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.id = undefined;
      // this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(num, row) {
      this.reset();
      if (num == 2) {
        const userId = row.id || this.ids;
        getChatUser(userId).then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改资料";
          this.show = true;
          this.imageUrl = row.avatar;
        });
      } else {
        this.show = false;
        this.open = true;
        this.title = "设置分组";
      }
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.ids.length != 0) {
            var data = {};
            data.ids = this.ids;
            data.groupId = this.form.groupId;
            groups(data).then((response) => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.form.id != undefined) {
              updateChatUser(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.imageUrl = "";
                this.fileList = [];
                this.getList();
              });
            } else {
              addChatUser(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids;
      this.$modal
        .confirm("确认删除数据吗？")
        .then(function () {
          return delChatUser(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss">
.touxiang {
  display: flex;
  .avatar-uploader {
    ::v-deep .el-upload {
      margin-top: 5px;
      height: 45px;
      display: flex;
      flex-direction: column;
      align-content: space-between;
    }
    ::v-deep .el-button {
      width: 90px;
      height: 35px;
      font-size: 15px;
    }
  }
  .pic {
    margin-right: 20px;
    border-radius: 50%;
    height: 80px;
    border: 1px dashed gray;
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 80px;
      height: 80px;
      line-height: 80px;
      text-align: center;
    }
    .avatar {
      border-radius: 50%;
      width: 80px;
      height: 80px;
      display: block;
      margin-top: -1px !important;
    }
  }
}
</style>
